import pythoncom , win32api, time
from win32com.taskscheduler import taskscheduler

#DONE

#create tasks into windows scheduler
#retreive task info
#delete tasks
#create the 24h cycle
#create the 1 month cycle
#create startup to launch the "daemon" when the computer is launched
#create a task that launch when the user logs in

def get_task_info(name):
    """return infos about a task"""
    ts = pythoncom.CoCreateInstance(taskscheduler.CLSID_CTaskScheduler,None, 
                                    pythoncom.CLSCTX_INPROC_SERVER,
                                    taskscheduler.IID_ITaskScheduler)
    if '%s.job' % name not in ts.Enum():
        raise KeyError("%s doesn't exists" % name)
    
    task = ts.Activate(name)
    return [task.GetTriggerString(i)
            for i in range(task.GetTriggerCount())]
    
def delete_task(name):
    """removes a task"""
    ts = pythoncom.CoCreateInstance(taskscheduler.CLSID_CTaskScheduler,None, 
                                    pythoncom.CLSCTX_INPROC_SERVER,
                                    taskscheduler.IID_ITaskScheduler)
    if '%s.job' % name not in ts.Enum():
        raise KeyError("%s doesn't exists" % name)
    ts.Delete(name)
    
def getListOfSchedTasks():
    ts = pythoncom.CoCreateInstance(taskscheduler.CLSID_CTaskScheduler,None, 
                                    pythoncom.CLSCTX_INPROC_SERVER,
                                    taskscheduler.IID_ITaskScheduler)
    return ts.Enum()
       
def create_task(name, cmd, type='Daily', hour=None, minute=None):
    """creates a task"""
    cmd = cmd.split()
    ts = pythoncom.CoCreateInstance(taskscheduler.CLSID_CTaskScheduler,None, 
                                    pythoncom.CLSCTX_INPROC_SERVER,
                                    taskscheduler.IID_ITaskScheduler)
    
    if '%s.job' % name in ts.Enum():
        print 'Deleting existing task '+name
        ts.Delete(name)


    if '%s.job' % name not in ts.Enum():
        task = ts.NewWorkItem(name)
        
        task.SetApplicationName(cmd[0])
        task.SetParameters(' '.join(cmd[1:]))
        task.SetPriority(taskscheduler.REALTIME_PRIORITY_CLASS)
        task.SetFlags(taskscheduler.TASK_FLAG_DELETE_WHEN_DONE|
                      taskscheduler.TASK_FLAG_RUN_ONLY_IF_LOGGED_ON)
        task.SetAccountInformation('', None)
        
        ts.AddWorkItem(name, task)
        run_time = time.localtime(time.time() + 300)
        tr_ind, tr = task.CreateTrigger()
        tt = tr.GetTrigger()
        tt.Flags = 0  
        tt.BeginYear = int(time.strftime('%Y', run_time))
        tt.BeginMonth = int(time.strftime('%m', run_time))
        tt.BeginDay = int(time.strftime('%d', run_time))
        if minute is None:
            tt.StartMinute = int(time.strftime('%M', run_time))
        else:
            tt.StartMinute = minute
        if hour is None:
            tt.StartHour = int(time.strftime('%H', run_time))
        else:
            tt.StartHour = hour
        if type=='Daily':
            tt.TriggerType = int(taskscheduler.TASK_TIME_TRIGGER_DAILY)
        #if type=='Weekly':
            #tt.TriggerType = taskscheduler.TASK_TIME_TRIGGER_WEEKLY
            #tt.weeks_interval=1
            #needs DaysOfWeek=1
            #needs interval
        if type=='Monthly':
            tt.TriggerType = taskscheduler.TASK_TIME_TRIGGER_MONTHLYDATE
            #months can contain multiples in a bitmask, use 1<<(month_nbr-1)
            tt.MonthlyDate_Months=1<<(int(time.strftime('%m',run_time))-1)
            #days too
            tt.MonthlyDate_Days=1<<(int(time.strftime('%d',run_time))-1)
        if type=='SystemStart':
            tt.TriggerType = taskscheduler.TASK_EVENT_TRIGGER_AT_SYSTEMSTART
        if type=='Loggon':
            tt.TriggerType = taskscheduler.TASK_EVENT_TRIGGER_AT_LOGON
        if type=='OnceDynamic':
            run_time = time.localtime(time.time() + 3600)
            tt.BeginYear = int(time.strftime('%Y', run_time))
            tt.BeginMonth = int(time.strftime('%m', run_time))
            tt.BeginDay = int(time.strftime('%d', run_time))
            if minute is None:
                tt.StartMinute = int(time.strftime('%M', run_time))
            else:
                tt.StartMinute = minute
            if hour is None:
                tt.StartHour = int(time.strftime('%H', run_time))
            else:
                tt.StartHour = hour
            tt.TriggerType = taskscheduler.TASK_TIME_TRIGGER_ONCE
        if type=='Once':
            tt.TriggerType = taskscheduler.TASK_TIME_TRIGGER_ONCE
            
        tr.SetTrigger(tt)
        pf = task.QueryInterface(pythoncom.IID_IPersistFile)
        pf.Save(None,1)
        task.Run()
    else:
        raise KeyError("%s already exists" % name)

    task = ts.Activate(name)
    exit_code, startup_error_code = task.GetExitCode()
    return win32api.FormatMessage(startup_error_code)

#if __name__ == "__main__":
    #create_task('EBT-Daily', '"c:\\python25\\python.exe" "C:\\Documents and Settings\\Feez\\workspace\\Core-IncrementalBackup\\src\\CoreHandling\\test.py"')
    #create_task('EBT-Monthly', '"c:\\python25\\python.exe" "C:\\Documents and Settings\\Feez\\workspace\\Core-IncrementalBackup\\src\\CoreHandling\\test.py"', 'Monthly')
    #create_task('EBT-SS', '"c:\\python25\\python.exe" "C:\\Documents and Settings\\Feez\\workspace\\Core-IncrementalBackup\\src\\CoreHandling\\test.py"', 'SystemStart')
    #create_task('EBT-Log', '"c:\\python25\\python.exe" "C:\\Documents and Settings\\Feez\\workspace\\Core-IncrementalBackup\\src\\CoreHandling\\test.py"', 'Loggon')
    #create_task('EBT-Once', '"c:\\python25\\python.exe" "C:\\Documents and Settings\\Feez\\workspace\\Core-IncrementalBackup\\src\\CoreHandling\\test.py"', 'Once')
    #print get_task_info('EBT-Log')